package websocketIoServer;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

//websocket协议
public class WsProtocol {
    private int x;
    static class Header{
        private Map<String,String> headers = new HashMap<>();
        String getHeader(String key){
            return headers.get(key);
        }
        static Header decodeFromHeadShakeDate(String handShakeData){
            String rowAndHead[] = handShakeData.split("\r\n");
            HttpObj httpObj = new HttpObj();

            String[] rowArr = rowAndHead[0].split(" ");
            httpObj.method = rowArr[0];
            httpObj.path = rowArr[1];
            httpObj.httpVersion = rowArr[2];
            Header header = new Header();
            for (int i = 1; i < rowAndHead.length; i++) {
                String[] headArr = rowAndHead[i].split(": ");
                if (headArr.length <2) continue;
                header.headers.put(headArr[0],headArr[1]);
            }
            httpObj.requestHead = header.headers;
            return header;
        }
    }
    static class HttpObj{
        public String method;
        public String path;
        public String httpVersion;
        public Map<String,String> requestHead;
        public String content;

    }

    static String getHandShakeResp(String reqKey){
        String wsAccept = reqKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
        MessageDigest sha1;
        try {
            sha1 = MessageDigest.getInstance("sha1");
            wsAccept = new String(Base64.getEncoder().encode(sha1.digest(wsAccept.getBytes())));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        String echoHeader = "";
        echoHeader += "HTTP/1.1 101 Switching Protocols\r\n";
        echoHeader += "Upgrade: websocket\r\n";
        echoHeader += "Connection: Upgrade\r\n";
        echoHeader += "Sec-WebSocket-Accept: " + wsAccept + "\r\n";
        echoHeader += "\r\n";
        System.out.println(echoHeader);
        return echoHeader;
    }

}
